/*
 * Copyright (C) 2014 Evgeniy Egorov
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ru.apertum.qsystem.client.forms;

import lombok.extern.log4j.Log4j2;
import ru.apertum.qsystem.client.help.Helper;
import ru.apertum.qsystem.client.model.QPanel;
import ru.apertum.qsystem.common.NetCommander;
import ru.apertum.qsystem.common.QConfig;
import ru.apertum.qsystem.common.Uses;
import ru.apertum.qsystem.common.exceptions.ClientException;
import ru.apertum.qsystem.common.exceptions.QException;
import ru.apertum.qsystem.common.model.INetProperty;
import ru.apertum.qsystem.hibernate.ChangeServerAction;
import ru.apertum.qsystem.server.model.QUser;
import ru.apertum.qsystem.server.model.QUserList;

import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.LayoutStyle;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.Scanner;

import static ru.apertum.qsystem.common.Uses.loc;

/**
 * Диалог выбора пользователя и ввода пароля.
 *
 * @author Evgeniy Egorov
 */
@SuppressWarnings({"squid:S1192", "squid:S1172", "squid:S1450", "squid:S1604", "squid:S1161", "squid:MaximumInheritanceDepth"})
@Log4j2
public class FLogin extends javax.swing.JDialog {

    /**
     * Результат.
     */
    private static boolean ok = false;
    /**
     * Количество неудачных попыток, если 0 то бесконечно.
     */
    private static int count = 0;
    private static int was = 0;
    /**
     * Параметры соединения.
     */
    private transient INetProperty netProperty;
    private QUserList userList;
    private JFrame parentFrame;
    /**
     * Уровни логирования.
     */
    public static final int LEVEL_USER = 1;
    public static final int LEVEL_REPORT = 2;
    public static final int LEVEL_ADMIN = 3;
    /**
     * текущий уровень доступа для диалога.
     */
    private int level = LEVEL_USER;

    public final int getLevel() {
        return level;
    }

    /**
     * Выведем на форму текст ооб уровне.
     *
     * @param level уровень.
     */
    public final void setLevel(int level) {
        this.level = level;
        passwordField.setText("");
        labelServer.setText("");
        switch (level) {
            case LEVEL_USER -> labelLavel.setText(LABEL_USER);
            case LEVEL_REPORT -> labelLavel.setText(LABEL_REPORT);
            case LEVEL_ADMIN -> {
                final ChangeServerAction as = new ChangeServerAction();
                if (as.getServers().size() > 1) {
                    labelServer.setText("<html>" + as.getTitle() + "<br>" + as.getUrl());
                }
                labelLavel.setText(LABEL_ADMIN);
            }
            default -> labelLavel.setText(LABEL_USER);
        }
    }

    /**
     * Надпись о доступе.
     */
    private static final String LABEL_USER = " " + loc("login.messages.access.work");
    private static final String LABEL_REPORT = " " + loc("login.messages.access.report");
    private static final String LABEL_ADMIN = " " + loc("login.messages.access.admin");

    /**
     * Используемая ссылка на диалоговое окно.
     */
    private static FLogin loginForm;

    /**
     * Creates new form FLogin.
     */
    public FLogin(INetProperty netProperty, JFrame parent, boolean modal, int level) {
        super(parent, modal);
        initComponents();
        init(null, netProperty, parent, modal, level);
    }

    /**
     * Creates new form FLogin.
     */
    public FLogin(QUserList userList, JFrame parent, boolean modal, int level) {
        super(parent, modal);
        initComponents();
        init(userList, null, parent, modal, level);
    }

    private QUser fastUser = null;

    /**
     * Тут надо четко понимать, что либо userList не NULL, либо netProperty не NULL.
     */
    private void init(QUserList userList, INetProperty netProperty, JFrame parent, boolean modal, int level) {
        try {
            setIconImage(ImageIO.read(Objects.requireNonNull(FLogin.class.getResource("/ru/apertum/qsystem/client/forms/resources/client.png"))));
        } catch (IOException ex) {
            log.error(ex);
        }
        setAlwaysOnTop(true);
        this.netProperty = netProperty;
        this.userList = userList;
        this.parentFrame = parent;
        this.userGetter = new GetUserFromServer();
        setLevel(level);

        final LinkedList<QUser> users;
        try {
            users = netProperty != null ? NetCommander.getUsers(netProperty) : userList.getItems();
        } catch (QException e) {
            log.error("Error login.", e);
            JOptionPane.showMessageDialog(null,
                    "Init was failed. " + e,
                    "Init",
                    JOptionPane.ERROR_MESSAGE);
            System.exit(1);
            throw new RuntimeException(e);
        }

        ArrayList<QUser> userArrayList = new ArrayList<>();
        for (QUser user : users) {
            if (user.getId().toString().equals(QConfig.cfg().getUserID())) {
                ok = true;
                fastUser = user;
                return;
            }

            boolean flag = switch (getLevel()) {
                case LEVEL_ADMIN -> user.getAdminAccess();
                case LEVEL_REPORT -> user.getReportAccess();
                case LEVEL_USER -> user.getServicesCnt() != 0;
                default -> throw new IllegalArgumentException("Strange level = " + getLevel());
            };

            if (flag) {
                userArrayList.add(user);
            }
        }
        afterCreate(userArrayList.toArray(QUser[]::new));
    }

    /**
     * Чтоб не дублировать код.
     *
     * @param users список пользователей.
     */
    private void afterCreate(QUser[] users) {
        FAbout.loadVersionSt();
        labelName.setText(FAbout.getQname());
        DefaultComboBoxModel<QUser> m = new DefaultComboBoxModel<>(users);
        comboBoxUser.setModel(m);
        final File f = new File("temp/lusr");
        if (f.exists()) {
            String str = loadFile(f);
            if (!"".equals(str) && str.matches("-?\\d+(\\.\\d+)?")) {
                for (int i = 0; i < m.getSize(); i++) {
                    if (((m.getElementAt(i))).getId().equals(Long.parseLong(str))) {
                        m.setSelectedItem(m.getElementAt(i));
                        break;
                    }
                }
            }
        }

        if (QConfig.cfg().getPointNs().length == 0) {
            cbPoint.setVisible(false);
            pointLab.setVisible(false);
        } else {
            cbPoint.setModel(new javax.swing.DefaultComboBoxModel<>(QConfig.cfg().getPointNs()));
            cbPoint.setSelectedIndex(0);
            cbPoint.setVisible(true);
            pointLab.setVisible(true);
        }
        //привязка помощи к форме.
        final Helper helper = Helper.getHelp(level == LEVEL_ADMIN ? "ru/apertum/qsystem/client/help/admin.hs" : "ru/apertum/qsystem/client/help/client.hs");
        helper.enableHelpKey(qPanel1, "loginning");
        // logo
        labelLogo.setText("<html>" +
                "╔═══╦═══╗──────╔╗<br>" +
                "║╔═╗║╔═╗║─────╔╝╚╗<br>" +
                "║║─║║╚══╦╗─╔╦═╩╗╔╬══╦╗╔╗<br>" +
                "║║─║╠══╗║║─║║══╣║║║═╣╚╝║<br>" +
                "║╚═╝║╚═╝║╚═╝╠══║╚╣║═╣║║║<br>" +
                "╚══╗╠═══╩═╗╔╩══╩═╩══╩╩╩╝<br>" +
                "───╚╝───╔═╝║<br>" +
                "────────╚══╝" +
                "");


        labelLogo.setText("<html>" +
                "╔═══╗╔══╗╔╗╔╗╔══╗╔════╗╔═══╗╔╗──╔╗<br>" +
                "║╔═╗║║╔═╝║║║║║╔═╝╚═╗╔═╝║╔══╝║║──║║<br>" +
                "║║─║║║╚═╗║╚╝║║╚═╗──║║──║╚══╗║╚╗╔╝║<br>" +
                "║║╔╝║╚═╗║╚═╗║╚═╗║──║║──║╔══╝║╔╗╔╗║<br>" +
                "║╚╝─║╔═╝║─╔╝║╔═╝║──║║──║╚══╗║║╚╝║║<br>" +
                "╚═══╝╚══╝─╚═╝╚══╝──╚╝──╚═══╝╚╝──╚╝" +
                "");

        labelLogo.setText("<html>" +
                "┏━━━┳━━━┓╋╋╋╋╋╋┏┓<br>" +
                "┃┏━┓┃┏━┓┃╋╋╋╋╋┏┛┗┓<br>" +
                "┃┃╋┃┃┗━━┳┓╋┏┳━┻┓┏╋━━┳┓┏┓<br>" +
                "┃┃╋┃┣━━┓┃┃╋┃┃━━┫┃┃┃━┫┗┛┃<br>" +
                "┃┗━┛┃┗━┛┃┗━┛┣━━┃┗┫┃━┫┃┃┃<br>" +
                "┗━━┓┣━━━┻━┓┏┻━━┻━┻━━┻┻┻┛<br>" +
                "╋╋╋┗┛╋╋╋┏━┛┃<br>" +
                "╋╋╋╋╋╋╋╋┗━━┛" +
                "");

        labelLogo.setText(LOGO_TEXT);
    }

    public static final String LOGO_TEXT = "<html>" +
            "╔╗ ╔╗ ║║ ╔╗ ╦ ╔═ ╔╦╗<br>" +
            "║║ ╚╗ ╚╣ ╚╗ ║ ╠═ ║║║<br>" +
            "╚╬ ╚╝ ═╝ ╚╝ ║ ╚═ ║║║<br>" +
            "";

    private String loadFile(File f) {
        StringBuilder str = new StringBuilder();
        try (FileInputStream fis = new FileInputStream(f);
             Scanner s = new Scanner(new InputStreamReader(fis, StandardCharsets.UTF_8))) {
            while (s.hasNextLine()) {
                final String line = s.nextLine().trim();
                str.append(line);
            }
        } catch (IOException ex) {
            log.error(ex);
        }
        return str.toString();
    }

    /**
     * Логирование без предварительно созданного списка пользователей. Этот список определяется путем отправки задания на сервер.
     *
     * @param netProperty свойства коннекта
     * @param owner       относительно этого контрола модальность и позиционирование
     * @param modal       режим модальности
     * @param count       количество неудачных попыток, если 0 то бесконечно
     * @param level       Уровень доступа, см. LEVEL_USER, LEVEL_REPORT, LEVEL_ADMIN
     * @return залогиневшiйся юзер.
     */
    public static QUser logining(INetProperty netProperty, JFrame owner, boolean modal, int count, int level) {
        log.info("Enter to the system.");
        if (loginForm == null) {
            loginForm = new FLogin(netProperty, owner, modal, level);
        } else {
            if (loginForm.netProperty != netProperty || loginForm.parentFrame != owner || loginForm.getLevel() != level) {
                loginForm = new FLogin(netProperty, owner, modal, level);
            }
        }
        FLogin.count = count;
        if (owner == null) {
            // Отцентирируем
            loginForm.setLocationRelativeTo(null);
        }
        Uses.closeSplash();
        if (!ok) {
            loginForm.setVisible(true);
        }
        if (!ok) {
            System.exit(0);
        }
        final QUser user = loginForm.fastUser != null ? loginForm.fastUser : (QUser) loginForm.comboBoxUser.getSelectedItem();
        log.info("Access successful. User \"{}\", Access level is \"{}\".", user, level);
        final File f = new File("temp/lusr");
        try {
            try (FileOutputStream fos = new FileOutputStream(f)) {
                assert user != null;
                fos.write(user.getId().toString().getBytes());
                fos.flush();
            }
        } catch (IOException ex) {
            log.error(ex);
        }
        return user;
    }

    /**
     * Логирование имея уже готовый список возможных пользователей для логирования.
     *
     * @param userList список пользователей
     * @param owner    относительно этого контрола модальность и позиционирование
     * @param modal    режим модальности
     * @param count    количество неудачных попыток, если 0 то бесконечно
     * @param level    Уровень доступа, см. LEVEL_USER, LEVEL_REPORT, LEVEL_ADMIN
     * @return залогиневшийся юзер.
     */
    public static QUser logining(QUserList userList, JFrame owner, boolean modal, int count, int level) {
        log.info("Вход в систему.");
        if (loginForm == null) {
            loginForm = new FLogin(userList, owner, modal, level);
        } else {
            if (loginForm.userList != userList || loginForm.parentFrame != owner || loginForm.getLevel() != level) {
                loginForm = new FLogin(userList, owner, modal, level);
            }
        }
        FLogin.count = count;
        if (owner == null) {
            // Отцентирируем
            loginForm.setLocationRelativeTo(null);
        }
        Uses.closeSplash();
        if (!ok) {
            loginForm.setVisible(true);
        }
        if (!ok) {
            System.exit(0);
        }
        final QUser user = loginForm.fastUser != null ? loginForm.fastUser : (QUser) loginForm.comboBoxUser.getSelectedItem();
        log.info("Вход в систему выполнен. Пользователь \"" + user + "\", уровень доступа \"" + level + "\".");
        final File f = new File("temp/lusr");
        try {
            try (FileOutputStream fos = new FileOutputStream(f)) {
                assert user != null;
                fos.write(user.getId().toString().getBytes());
                fos.flush();
            }
        } catch (IOException ex) {
            log.error(ex);
        }
        return user;
    }

    /**
     * Получить выбранного юзера по его имени для разных случаев.
     */
    @FunctionalInterface
    private interface IGetUser {

        QUser getUser();
    }

    private transient IGetUser userGetter;

    private class GetUserFromServer implements IGetUser {

        @Override
        public QUser getUser() {
            return fastUser != null ? fastUser : (QUser) comboBoxUser.getSelectedItem();
        }
    }

    private boolean checkLogin() {
        final QUser user = userGetter.getUser();
        switch (getLevel()) {
            case LEVEL_ADMIN:
                if (!user.getAdminAccess()) {
                    JOptionPane.showMessageDialog(this, loc("login.messages.noAccess.mess"), loc("login.messages.noAccess.caption"), JOptionPane.ERROR_MESSAGE);
                    return false;
                }
                break;
            case LEVEL_REPORT:
                if (!user.getReportAccess()) {
                    JOptionPane.showMessageDialog(this, loc("login.messages.noAccess.mess"), loc("login.messages.noAccess.caption"), JOptionPane.ERROR_MESSAGE);
                    return false;
                }
                break;
            case LEVEL_USER:
                break;
            default:
                throw new ClientException("Нет такого уровня доступа.");
        }

        final String userPass = user.getParolcheg();
        if (!userPass.equals(new String(passwordField.getPassword()))) {
            JOptionPane.showMessageDialog(this, loc("login.messages.noAccessUser.mess"), loc("login.messages.noAccess.caption"), JOptionPane.ERROR_MESSAGE);
            return false;
        }
        return true;
    }

    /**
     * Нажали ОК. Проверить палодьчег и принять решение. Закрыть форму.
     */
    public void pressOK() {
        ok = checkLogin();
        if (ok) {
            QConfig.cfg().setPointPos(cbPoint.getSelectedIndex());
            this.setVisible(false);
        } else {
            was++;
            if (was == count) {
                System.exit(0);
            }
        }
    }

    public void pressCancel() {
        System.exit(0);
    }

    private void keyPress(java.awt.event.KeyEvent evt) {

        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            pressOK();
        }
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            System.exit(0);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    // Generated using JFormDesigner non-commercial license
    private void initComponents() {
        ResourceBundle bundle = ResourceBundle.getBundle("ru.apertum.qsystem.common.resources.locale");
        qPanel1 = new QPanel();
        labelLavel = new JLabel();
        labelServer = new JLabel();
        labelName = new JLabel();
        jPanel6 = new JPanel();
        buttonExit = new JButton();
        buttonEnter = new JButton();
        cbPoint = new JComboBox<>();
        pointLab = new JLabel();
        passwordField = new JPasswordField();
        jLabel2 = new JLabel();
        comboBoxUser = new JComboBox<>();
        jLabel1 = new JLabel();
        labelLabel = new JLabel();
        labelLogo = new JLabel();

        //======== this ========
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setUndecorated(true);
        setResizable(false);
        var contentPane = getContentPane();

        //======== qPanel1 ========
        {
            qPanel1.setBorder(null);

            //---- labelLavel ----
            labelLavel.setFont(new Font("Tahoma", Font.PLAIN, 12));
            labelLavel.setForeground(Color.red);
            labelLavel.setText("ComponentOfSystem");

            //---- labelServer ----
            labelServer.setFont(new Font("Tahoma", Font.PLAIN, 10));
            labelServer.setForeground(Color.orange);
            labelServer.setText("serverBD");

            //---- labelName ----
            labelName.setFont(new Font("Tahoma", Font.PLAIN, 12));
            labelName.setHorizontalAlignment(SwingConstants.RIGHT);
            labelName.setText("jLabel4");

            //======== jPanel6 ========
            {
                jPanel6.setBorder(null);
                jPanel6.setOpaque(false);

                //---- buttonExit ----
                buttonExit.setText(bundle.getString("login.cancel"));
                buttonExit.addActionListener(e -> buttonExitActionPerformed(e));
                buttonExit.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyPressed(KeyEvent e) {
                        buttonExitKeyPressed(e);
                    }
                });

                //---- buttonEnter ----
                buttonEnter.setText(bundle.getString("login.enter"));
                buttonEnter.addActionListener(e -> {
                    buttonEnterActionPerformed(e);
                    buttonEnterActionPerformed(e);
                });
                buttonEnter.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyPressed(KeyEvent e) {
                        buttonEnterKeyPressed(e);
                    }
                });

                //---- pointLab ----
                pointLab.setText(bundle.getString("login.point"));
                pointLab.setLabelFor(cbPoint);

                //---- passwordField ----
                passwordField.setText("jPasswordField1");
                passwordField.setFont(passwordField.getFont().deriveFont(passwordField.getFont().getSize() + 3f));
                passwordField.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyPressed(KeyEvent e) {
                        passwordFieldKeyPressed(e);
                    }
                });

                //---- jLabel2 ----
                jLabel2.setText(bundle.getString("login.password"));

                //---- comboBoxUser ----
                comboBoxUser.addKeyListener(new KeyAdapter() {
                    @Override
                    public void keyPressed(KeyEvent e) {
                        comboBoxUserKeyPressed(e);
                    }
                });

                //---- jLabel1 ----
                jLabel1.setText(bundle.getString("login.user"));

                GroupLayout jPanel6Layout = new GroupLayout(jPanel6);
                jPanel6.setLayout(jPanel6Layout);
                jPanel6Layout.setHorizontalGroup(
                        jPanel6Layout.createParallelGroup()
                                .addGroup(jPanel6Layout.createSequentialGroup()
                                        .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGroup(jPanel6Layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                                .addGroup(jPanel6Layout.createSequentialGroup()
                                                        .addComponent(buttonEnter, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
                                                        .addGap(18, 18, 18)
                                                        .addComponent(buttonExit, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE))
                                                .addGroup(jPanel6Layout.createSequentialGroup()
                                                        .addGroup(jPanel6Layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                                                .addComponent(pointLab)
                                                                .addComponent(jLabel1)
                                                                .addComponent(jLabel2))
                                                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                                        .addGroup(jPanel6Layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                                                                .addComponent(cbPoint, GroupLayout.Alignment.TRAILING)
                                                                .addComponent(passwordField, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE)
                                                                .addComponent(comboBoxUser, GroupLayout.Alignment.TRAILING))))
                                        .addContainerGap())
                );
                jPanel6Layout.setVerticalGroup(
                        jPanel6Layout.createParallelGroup()
                                .addGroup(GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                                        .addContainerGap()
                                        .addGroup(jPanel6Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                .addComponent(comboBoxUser, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                                .addComponent(jLabel1))
                                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel6Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                .addComponent(passwordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                                .addComponent(jLabel2))
                                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel6Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                .addComponent(cbPoint, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                                .addComponent(pointLab))
                                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(jPanel6Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                .addComponent(buttonExit)
                                                .addComponent(buttonEnter))
                                        .addContainerGap())
                );
            }

            //---- labelLabel ----
            labelLabel.setIcon(new ImageIcon(getClass().getResource("/ru/apertum/qsystem/client/forms/resources/label.png")));

            //---- labelLogo ----
            labelLogo.setText("<html>logo here from code.");
            labelLogo.setFont(new Font(Font.MONOSPACED, Font.BOLD, 30));

            GroupLayout qPanel1Layout = new GroupLayout(qPanel1);
            qPanel1.setLayout(qPanel1Layout);
            qPanel1Layout.setHorizontalGroup(
                    qPanel1Layout.createParallelGroup()
                            .addGroup(qPanel1Layout.createSequentialGroup()
                                    .addContainerGap()
                                    .addGroup(qPanel1Layout.createParallelGroup()
                                            .addGroup(GroupLayout.Alignment.TRAILING, qPanel1Layout.createSequentialGroup()
                                                    .addGroup(qPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                                            .addComponent(labelLogo, GroupLayout.DEFAULT_SIZE, 688, Short.MAX_VALUE)
                                                            .addGroup(qPanel1Layout.createSequentialGroup()
                                                                    .addComponent(labelLabel)
                                                                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                                                    .addComponent(labelName, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                                    .addGap(9, 9, 9))
                                            .addGroup(GroupLayout.Alignment.TRAILING, qPanel1Layout.createSequentialGroup()
                                                    .addComponent(labelLavel, GroupLayout.DEFAULT_SIZE, 691, Short.MAX_VALUE)
                                                    .addContainerGap())
                                            .addGroup(GroupLayout.Alignment.TRAILING, qPanel1Layout.createSequentialGroup()
                                                    .addComponent(labelServer, GroupLayout.DEFAULT_SIZE, 691, Short.MAX_VALUE)
                                                    .addContainerGap())
                                            .addGroup(GroupLayout.Alignment.TRAILING, qPanel1Layout.createSequentialGroup()
                                                    .addGap(0, 440, Short.MAX_VALUE)
                                                    .addComponent(jPanel6, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
            );
            qPanel1Layout.setVerticalGroup(
                    qPanel1Layout.createParallelGroup()
                            .addGroup(qPanel1Layout.createSequentialGroup()
                                    .addGroup(qPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                                            .addGroup(qPanel1Layout.createSequentialGroup()
                                                    .addContainerGap()
                                                    .addComponent(labelLabel))
                                            .addComponent(labelName, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGap(18, 18, 18)
                                    .addComponent(labelLogo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 108, Short.MAX_VALUE)
                                    .addComponent(jPanel6, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(labelServer)
                                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(labelLavel)
                                    .addContainerGap())
            );
        }

        GroupLayout contentPaneLayout = new GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(
                contentPaneLayout.createParallelGroup()
                        .addComponent(qPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        contentPaneLayout.setVerticalGroup(
                contentPaneLayout.createParallelGroup()
                        .addComponent(qPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        pack();
        setLocationRelativeTo(getOwner());
    }// </editor-fold>//GEN-END:initComponents

    private void buttonEnterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEnterActionPerformed
        pressOK();
    }//GEN-LAST:event_buttonEnterActionPerformed

    private void buttonExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExitActionPerformed
        pressCancel();
    }//GEN-LAST:event_buttonExitActionPerformed

    private void comboBoxUserKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_comboBoxUserKeyPressed
        keyPress(evt);
    }//GEN-LAST:event_comboBoxUserKeyPressed

    private void passwordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordFieldKeyPressed
        keyPress(evt);
    }//GEN-LAST:event_passwordFieldKeyPressed

    private void buttonEnterKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_buttonEnterKeyPressed
        keyPress(evt);
    }//GEN-LAST:event_buttonEnterKeyPressed

    private void buttonExitKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_buttonExitKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            pressCancel();
        }
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            System.exit(0);
        }
    }//GEN-LAST:event_buttonExitKeyPressed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    // Generated using JFormDesigner non-commercial license
    private QPanel qPanel1;
    private JLabel labelLavel;
    private JLabel labelServer;
    private JLabel labelName;
    private JPanel jPanel6;
    private JButton buttonExit;
    private JButton buttonEnter;
    private JComboBox<String> cbPoint;
    private JLabel pointLab;
    private JPasswordField passwordField;
    private JLabel jLabel2;
    private JComboBox<QUser> comboBoxUser;
    private JLabel jLabel1;
    private JLabel labelLabel;
    private JLabel labelLogo;
    // End of variables declaration//GEN-END:variables
}
